package com.hengxinguotong.zhihuichengjian.receiver;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.bean.Message;
import com.hengxinguotong.zhihuichengjian.floatwindow.MyWindowManager;
import com.hengxinguotong.zhihuichengjian.ui.MainActivity;
import com.hengxinguotong.zhihuichengjian.ui.MessageActivity;
import com.hengxinguotong.zhihuichengjian.ui.SearchPersonActivity;
import com.hengxinguotong.zhihuichengjian.ui.engineering.reservation.ReservationListActivity;
import com.hengxinguotong.zhihuichengjian.ui.engineering.task.TaskListActivity;
import com.hengxinguotong.zhihuichengjian.ui.quality.RectificationListActivity;
import com.hengxinguotong.zhihuichengjian.utils.ActivityController;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.view.CustomPatient;
import com.orhanobut.logger.Logger;

import org.json.JSONException;
import org.json.JSONObject;


import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.CustomPushNotificationBuilder;
import cn.jpush.android.api.DefaultPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * <p/>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {


    @Override
    public void onReceive(final Context context, Intent intent) {

        Bundle bundle = intent.getExtras();

        if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
            String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
//            Log.i("test","message"+message);
            String map = bundle.getString(JPushInterface.EXTRA_EXTRA);
            JSONObject json = null;
            try {
                json = new JSONObject(map);
                int type = Integer.parseInt(json.getString("type"));//消息类型：0.系统消息； 1.质量整改； 2.安全整改； 3.任务派发； 4.塔吊预约； 5.升降机预约
                updateMenu(type);
//                sendNotification(context, title, message, type);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if(JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())){
            String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
            String message = bundle.getString(JPushInterface.EXTRA_ALERT);
//            sendNotification(context, title, message);
//                // 获得广播发送的数据
//                final String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
            String map = bundle.getString(JPushInterface.EXTRA_EXTRA);
            JSONObject json = null;
            try {
                json = new JSONObject(map);
                int type = Integer.parseInt(json.getString("type"));//消息类型：0.系统消息； 1.质量整改； 2.安全整改； 3.任务派发； 4.塔吊预约； 5.升降机预约
//                int status = json.getInt("status");//1:待受理; 2:处理中;3:待检查;4:检查不通过；5:已完成
                updateMenu(type);
            } catch (JSONException e) {
                e.printStackTrace();
            }
//                String message = bundle.getString(JPushInterface.EXTRA_ALERT);
        }
        if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Logger.d("ACTION_NOTIFICATION_OPENED");
            //打开自定义的Activity
            Intent i = new Intent(context, MessageActivity.class);
            i.putExtras(bundle);
            //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(i);
        }

    }

    private void updateMenu(int type){
//        Activity activity = ActivityController.getCurrentActivity();
        List<Activity> activities = ActivityController.getActivities();
        for(Activity activity:activities){
            if(activity instanceof MainActivity){
                ((MainActivity)activity).setNotRead(type);
            }
        }
    }

    private static int NOTIFY_ID = 1000;

    private void sendJPushNotification(Context context, String title, String message){
//        CustomPushNotificationBuilder builder = new CustomPushNotificationBuilder(
//                context, R.layout.layout_notification, R.
//        )
    }

    private void sendNotification(Context context, String title, String message, int type) {
        //【1】获取Notification 管理器
        NotificationManager notifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        //【2】设置通知。PendingIntent表示延后触发，是在用户下来状态栏并点击通知时触发，触发时PendingIntent发送intent打开到指定页面。
        Intent intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //intent.setComponent(new ComponentName(this, MainActivity.class));  //方法4
        // 主要设置点击通知的时显示内容的类
        PendingIntent pi = PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
//        Notification.Builder builder = new Notification.Builder(context)
        builder.setSmallIcon(R.mipmap.ic_launcher)//设置通知栏上的小图标
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
                .setDefaults(Notification.DEFAULT_ALL)//通知类型;1只声音；2只震动；3声音+震动
                .setTicker("智慧城建")//通知App名称显示
                .setContentTitle(title)//通知标题
                .setWhen(System.currentTimeMillis())//通知的时间
                .setContentText(message)//通知内容
                .setContentIntent(pi);//点击通知跳转向
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            builder.setVisibility(Notification.VISIBILITY_PUBLIC);//设置通知的显示等级，PUBLIC在任何地方都可看得到VISIBILITY_PRIVATE：如果你手机上了 pin，解锁 pin 过后才能看到通知VISIBILITY_SECRET：在任何地方都看不到
            //这个方法很重要，这也就是区别于其他普通Notification的设置方法,作用：让通知栏弹出来
            builder.setFullScreenIntent(pi, true);// 横幅,两个参数：即将发生的intent；设置是否只显示一条通知栏消息
        }
        Notification notification = builder.build();
//        notification.vibrate= new long[]{ 100 };
        notification.flags = Notification.FLAG_AUTO_CANCEL; //点击后删除，如果是FLAG_NO_CLEAR则不删除，FLAG_ONGOING_EVENT用于某事正在进行，例如电话，具体查看参考。
        //【3】发送通知到通知管理器。第一个参数是这个通知的唯一标识，通过这个id可以在以后cancel通知，更新通知（发送一个具有相同id的新通知）。这个id在应用中应该是唯一的。
        notifyMgr.notify(NOTIFY_ID, notification);
        updateMenu(type);
    }

}
